package com.texas_android.app.View;

import android.Manifest;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.ui.RecognizerDialog;
import com.iflytek.cloud.ui.RecognizerDialogListener;
import com.texas_android.app.R;
import com.texas_android.app.utils.JsonParser;
import com.texas_android.app.utils.Logger;
import com.universal_library.activity.BaseActivity;
import com.universal_library.permission.Acp;
import com.universal_library.permission.AcpListener;
import com.universal_library.permission.AcpOptions;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

public class TestActivity extends BaseActivity implements View.OnClickListener {
    @Bind(R.id.tv_speakTest)
    EditText tv_speakTest;

    @Bind(R.id.bt_speak)
    Button bt_speak;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_test;
    }

    // 用HashMap存储听写结果
    private HashMap<String, String> mIatResults = new LinkedHashMap<String, String>();

    @Override
    protected void initView() {

    }

    @Override
    protected void initData() {

    }

    @OnClick({R.id.bt_speak})
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_speak:
                Acp.getmInstance(this).request(new AcpOptions.Builder().setPermissions(Manifest.permission.RECORD_AUDIO).build(), new AcpListener() {
                    @Override
                    public void onGranted() {
                        startSpeechDialog();
                    }
                    @Override
                    public void onDenied(List<String> permissions) {
                    }
                });
                break;
        }
    }

    private void startSpeechDialog() {
        //1. 创建RecognizerDialog对象
        RecognizerDialog mDialog = new RecognizerDialog(this, new MyInitListener());
        //2. 设置accent、 language等参数
        mDialog.setParameter(SpeechConstant.LANGUAGE, "zh_cn");// 设置中文
        mDialog.setParameter(SpeechConstant.ACCENT, "mandarin");
        // 若要将UI控件用于语义理解，必须添加以下参数设置，设置之后 onResult回调返回将是语义理解
        // 结果
//         mDialog.setParameter("asr_sch", "1");
//         mDialog.setParameter("nlp_version", "3.0");
        //3.设置回调接口
        mDialog.setListener(new MyRecognizerDialogListener());
        //4. 显示dialog，接收语音输入
        mDialog.show();
    }

    class MyRecognizerDialogListener implements RecognizerDialogListener {

        /**
         * @param results
         * @param isLast  是否说完了
         */
        @Override
        public void onResult(RecognizerResult results, boolean isLast) {
            String result = results.getResultString(); //为解析的

            System.out.println(" 没有解析的 :" + result);

            String text = JsonParser.parseIatResult(result);//解析过后的
            System.out.println(" 解析后的 :" + text);

            String sn = null;
            // 读取json结果中的 sn字段
            try {
                JSONObject resultJson = new JSONObject(results.getResultString());
                sn = resultJson.optString("sn");
            } catch (JSONException e) {
                e.printStackTrace();
            }

            mIatResults.put(sn, text);//没有得到一句，添加到

            StringBuffer resultBuffer = new StringBuffer();
            for (String key : mIatResults.keySet()) {
                resultBuffer.append(mIatResults.get(key));
            }

            tv_speakTest.setText(resultBuffer.toString());// 设置输入框的文本
            tv_speakTest.setSelection(tv_speakTest.length());//把光标定位末尾
        }

        @Override
        public void onError(SpeechError speechError) {

        }
    }

    class MyInitListener implements InitListener {

        @Override
        public void onInit(int code) {
            if (code != ErrorCode.SUCCESS) {
                Logger.log("初始化失败");
            }

        }
    }
}
